#!/bin/sh
#1. get total number of questions: numq
#2. get max in_links: maxq (A+B = 1/2(numq*maxq)
#3. calculate B: sum all the in_link numbers
if [ $# -lt 2 ] 
then
    echo "Usage: ./calGiniIndex.sh in_link_count_fillZero.sort giniRetFile";
    echo "input File structure:"
    echo "id1""\t""in_link_num"
    echo "NOTICE: giniRetFile will be delete firstly"
    exit 1;
else
    src_file=$1
    dst_file=$2
fi
if [ -f $2 ] 
then
    rm $2
fi
#totalNum=`wc -l $src_file | awk '{print $1}'`
#echo $totalNum
#maxInlinkNum=`tail -1 $src_file | awk '{print $2}'`
#echo $maxInlinkNum

awk -v dstFile=$2 ' BEGIN{
#    printf("%.1f", 0.5 * totalNum * maxInlinkNum);
    totalLink = 0;
    BArea = 0;
    totalNum = 0;
}
{
    totalLink += $2;
    BArea += totalLink;
    ++totalNum;
    print NR, totalLink >> dstFile;
#    if ($2 > maxInlinkNum) {
#        maxInlinkNum = $2; 
#    }
}
END{
    totalArea =  0.5 * totalNum * totalLink;
    printf("%.5f\n", (totalArea-BArea)/totalArea);
}' $src_file
